package org.opens.predicate;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 说明:
 * <pre>
 *     1. 开发自定义断言需要注意以下事项:
 *      - 如果自定义的断言名称期望为Val, 则这个类必须命名为ValRoutePredicateFactory;
 *      - 必须继承AbstractRoutePredicateFactory;
 *      - 必须注册到spring容器中;
 *
 * </pre>
 */
@Component
public class ValRoutePredicateFactory extends AbstractRoutePredicateFactory<ValRoutePredicateFactory.Config> {

    public ValRoutePredicateFactory() {
        super(ValRoutePredicateFactory.Config.class);
    }

    // 读取配置文件中的参数值, 然后赋值给配置类中的属性上
    public List<String> shortcutFieldOrder() {
        // 注意的是-这个位置的顺序必须和配置文件中的值的顺序相同
        return Arrays.asList("minVal", "maxVal");
    }

    public Predicate<ServerWebExchange> apply(ValRoutePredicateFactory.Config config) {
        // exchange是webflux环境下的web参数, 类似于request, 可以从中获取请求参数.
        return (exchange) -> {
            String val = exchange.getRequest().getQueryParams().getFirst("val");

            if (StringUtils.isEmpty(val)) {
                return false;
            }

            int valInt = Integer.parseInt(val);
            return valInt >= config.minVal && valInt <= config.maxVal;
        };
    }

    @Data
    @NoArgsConstructor
    public static class Config {

        private Integer minVal;

        private Integer maxVal;

    }

}
